#encoding=utf-8
from bottle import TEMPLATE_PATH, Bottle, view, redirect, debug, response
from datetime import datetime, timedelta
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from model import Category, Article, Sequence, Comment, Tag
from utils import check_login, convertArticle, allcate, page_size, decode_param, \
    decode_post_param, login_required

myapp = Bottle()

@myapp.route('/')
@myapp.route('/page/:page#\d+#')
@view('index')
def index(page=1):
    page = int(page)
    queryArticle = Article.gql("order by create_date desc")
    page_cnt = (queryArticle.count() - 1) / page_size + 1
    articles = queryArticle.fetch(page_size, (page - 1) * page_size)
    articles = [convertArticle(art) for art in articles]
    current_page = page
    page_link_prefix = ""
    return locals()

@myapp.route('/tag/:tag')
@myapp.route('/tag/:tag/page/:page#\d+#')
@view('index')
@decode_param
def tag(tag, page=1):
    page = int(page)
    tags = Tag.gql("where val = :1", tag)
    queryArticle = []
    for item in tags:
        art = Article.gql("where id = :1", item.art_id).get()
        queryArticle.append(art)
    queryArticle = [convertArticle(art) for art in queryArticle]
    page_cnt = (len(queryArticle) - 1) / page_size + 1
    offset = (page - 1) * page_size
    articles = queryArticle[offset:offset + page_size]
    current_page = page
    page_link_prefix = "/tag/%s" % tag
    return locals()

@myapp.route('/viewcategory/:id#\d+#')
@myapp.route('/viewcategory/:id#\d+#/page/:page#\d+#')
@view('index')
def viewcategory(id, page=1):
    page = int(page)
    queryArticle = Article.gql("where category_id = :1 order by create_date desc" , int(id))
    page_cnt = (queryArticle.count() - 1) / page_size + 1
    articles = queryArticle.fetch(page_size, (page - 1) * page_size)
    articles = [convertArticle(art) for art in articles]
    current_page = page
    page_link_prefix = "/viewcategory/%d" % int(id)
    return locals()

@myapp.route('/viewdate/:bydate')
@myapp.route('/viewdate/:bydate/page/:page#\d+#')
@view('index')
def viewdate(bydate, page=1):
    page = int(page)
    queryArticle = Article.gql("order by create_date desc")
    queryArticle = [art for art in [convertArticle(art) for art in queryArticle ] if art.create_date.strftime("%Y年%m月") == bydate]
    page_cnt = (len(queryArticle) - 1) / page_size + 1
    offset = (page - 1) * page_size
    articles = queryArticle[offset:offset + page_size]
    current_page = page
    page_link_prefix = "/viewdate/%s" % bydate
    return locals()

@myapp.route('/viewarticle/:id#\d+#')
@view('article')
def viewarticle(id):
    auth = check_login()
    art = Article.gql("where id = :1" , int(id)).get()
    if not auth:
        art.view_cnt = art.view_cnt + 1
        art.put()
    art = convertArticle(art)
    comments = Comment.gql('where art_id = :1 order by create_date desc', int(art.id))
    data = {'username':'', 'content':''}
    error = ''
    return locals()

@myapp.route('/addcategory')
@view('addcategory')
@login_required('/addcategory')
def addcategory():
    error = ""
    return locals()
    
@myapp.route('/savecategory', method='POST')
@view('addcategory')
@decode_post_param
def savecategory(cate_name, cate_desc):
    ##validate
    if cate_name == "":
        error = "请输入类别的名称！"
        return locals()
        
    seq = Sequence.gql("where name=:1", 'category').get()
    cate = Category(id=seq.value, cate_name=cate_name, cate_desc=cate_desc)
    seq.value = seq.value + 1
    seq.put()
    cate.put()
    redirect('/')

@myapp.route('/addarticle')
@view('addarticle')
@login_required('/addarticle')
def addarticle():
    data = {"subject":'', "category_id":0, "shortness_content":'', "full_content":'', "tags":''}
    categories = allcate()
    error = ""
    return locals()
    
@myapp.route('/savearticle', method='POST')
@view('addarticle')
@decode_post_param
def savearticle(subject, category_id, shortness_content, full_content, tags, forwardFlag):
    ##validate
    if subject == "" or category_id == "" or shortness_content == "" or full_content == "":
        data = {"subject":subject, "category_id":category_id, "shortness_content":shortness_content, "full_content":full_content, "tags":tags}
        categories = allcate()
        error = "请输入完整！"
        return locals()

    art_seq = Sequence.gql("where name=:1", 'article').get()
    article_id = art_seq.value;
    article = Article(id=article_id, subject=subject,
                      shortness_content=shortness_content,
                      full_content=full_content,
                      category_id=int(category_id),
                      create_date=datetime.utcnow() + timedelta(hours= +8))
    art_seq.value = art_seq.value + 1
    art_seq.put()
    article.put()
    if tags:
        tags = tags.split(",")
        for item in tags:
            tag = Tag(val=item, art_id=article_id)
            tag.put()
            
    if forwardFlag == "true":
        redirect('/addarticle')
    else:
        redirect('/')
    
@myapp.route('/savecomment', method='POST')
@view('article')
@decode_post_param
def savecomment(art_id, username, content):
    art = convertArticle(Article.gql("where id = :1" , int(art_id)).get())
    comments = Comment.gql('where art_id = :1 order by create_date desc', int(art.id))
    
    if username == '' or content == '' or len(username) > 60 or len(content) > 2100:
        data = {'username':username, 'content':content}
        error = "请录入完整！"
        return locals()
    
    seq = Sequence.gql("where name=:1", 'comment').get()
    comment = Comment(id=seq.value, username=username,
                      content=content,
                       art_id=int(art_id),
                       create_date=datetime.utcnow() + timedelta(hours= +8))
    seq.value = seq.value + 1
    seq.put()
    comment.put()
    return redirect('/viewarticle/' + art_id)

@myapp.route('/editarticle/:id#\d+#')
@view('editarticle')
@login_required('/editarticle/:id')
def editarticle(id):
    art = Article.gql("where id = :1" , int(id)).get()
    tags = Tag.gql("where art_id = :1", art.id)
    tags = ",".join([tag.val for tag in tags])
    data = {"id":art.id, "subject":art.subject, "category_id":art.category_id, "shortness_content":art.shortness_content, "full_content":art.full_content, "tags":tags}
    categories = allcate()
    error = ''
    return locals()


@myapp.route('/updatearticle', method='POST')
@view('editarticle')
@decode_post_param
def updatearticle(id, subject, category_id, shortness_content, full_content, tags):
    ##validate
    if subject == "" or category_id == "" or shortness_content == "" or full_content == "":
        data = {"id":id, "subject":subject, "category_id":category_id, "shortness_content":shortness_content, "full_content":full_content, "tags":tags}
        error = "请输入完整！"
        categories = allcate()
        return locals()

    art = Article.gql('where id = :1', int(id)).get()
    art.subject = subject
    art.shortness_content = shortness_content
    art.full_content = full_content
    art.category_id = int(category_id)
    art.update_date = datetime.utcnow() + timedelta(hours= +8)
    art.put()
    
    if tags:
        items = Tag.gql("where art_id = :1", art.id)
        db.delete(items)
        tags = tags.split(",")
        for item in tags:
            tmp = Tag(val=item, art_id=art.id)
            tmp.put()
            
    return redirect('/viewarticle/' + id)

@myapp.route('/deletearticle/:id#\d+#')
@login_required('/deletearticle/:id')
def deletearticle(id):
    article = Article.gql('where id = :1', int(id)).get()
    article.delete()
    comments = Comment.gql('where art_id = :1', int(id))
    db.delete(comments)
    tags = Tag.gql("where art_id = :1", int(id))
    db.delete(tags)
    return redirect('/')

        
@myapp.route('/upload', method='POST')       
def upload():
    pass
    
@myapp.route('/sitemap')
def sitemap():
    response.content_type = 'text/xml'
    str = []
    str.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
    str.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">")
    for art in Article.all():
        str.append("<url>")
        str.append("<loc>http://bottleapp.appspot.com/viewarticle/%d</loc>" % art.id)
        str.append("<changefreq>daily</changefreq>")
        str.append("<priority>1</priority>") 
        str.append("</url>")
    str.append("</urlset>")
    return "".join(str)

@myapp.route('/searchresult')
@view('searchresult')
def searchresult():
    return dict()

##################################################################
def initSeq(name, value):
    seq = Sequence.gql("where name=:1", name).get()
    if not seq:
        seq = Sequence(name=name, value=value)
        seq.put()
        
#@myapp.route('/test')
#def test():
#    for i in range(100):
#        art = Article(id=i, subject="test%d" % i,
#                      shortness_content="test_shortness_content%d" % i,
#                      full_content="test_full_content%d" % i,
#                      category_id=50001,
#                      create_date=datetime.utcnow() + timedelta(hours= +8))
#        art.put()
##
if __name__ == '__main__':
    TEMPLATE_PATH.append('./template')
    debug(True)
    initSeq('category', 50001)
    initSeq('article', 60001)
    initSeq('comment', 70001)
    #run(app=myapp, server=AppEngineServer)
    util.run_wsgi_app(myapp)

